//
//  STStoryCommentViewModel.swift
//  Story
//
//  Created by 汤泽川 on 2019/4/24.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import PKHUD

class STStoryCommentViewModel {
    let commentId : Int?
    let storyId : Int?
    let service = STCommentService()
    var page = 0
    var count = 10
    let data = BehaviorRelay<[STCommentInfo]>(value: [])
    let collectState = BehaviorRelay<Bool>(value: false)
    let followState = BehaviorRelay<Bool>(value: false)
    let endRefresh = PublishSubject<Bool>()
    let disposeBag = DisposeBag()
    let authorId : Int
    
    init(commentId : Int?, storyId : Int?, authorId : Int) {
        self.authorId = authorId
        self.commentId = commentId
        self.storyId = storyId
        if storyId != nil {
            STCollectService().queryCollectState(storyId: storyId!).result {[weak self] (state, error) in
                self?.collectState.accept(state!)
            }
        }
        func quaryFollowStatus() {
            STUserService.shareInstance.quaryFollowStatus(targetId: authorId).result { (status, error) in
                if status == 1 {
                    self.followState.accept(true)
                } else {
                    self.followState.accept(false)
                }
            }
        }
        quaryFollowStatus()
        STUserService.shareInstance.currentUser.subscribe(onNext: { (userInfo) in
            quaryFollowStatus()
        }).disposed(by: disposeBag)
    }
    
    func isStory() -> Bool {
        return self.storyId != nil
    }
    
    func bindTableView(tableView : UITableView) {
        tableView.register(STCommentTableViewCell.self, forCellReuseIdentifier: "\(STCommentTableViewCell.self)")
        tableView.gtm_addLoadMoreFooterView { [weak self] in
            self?.loadMore()
        }
        endRefresh.subscribe(onNext: { (result) in
            tableView.endLoadMore(isNoMoreData: result)
        }).disposed(by: disposeBag)
        self.data.bind(to: tableView.rx.items) { (tableView, row, element) in
            let cell : STCommentTableViewCell = tableView.dequeueReusableCell(withIdentifier: "\(STCommentTableViewCell.self)") as! STCommentTableViewCell
            cell.configureCell(model: element)
            cell.selectionStyle = .none
            return cell
            }.disposed(by: disposeBag)
    }
    
    func changeFollowStatus() {
        self.followState.accept(!self.followState.value)
        STUserService.shareInstance.changeFollowStatus(targetId: self.authorId, status: self.followState.value ? 1 : 0).result { (error) in
            if error != nil {
                HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
                self.followState.accept(!self.followState.value)
            }
        }
    }
    
    func loadMore() {
        self.service.queryCommentInfo(replayId: self.commentId, storyId: self.storyId, page: page, count: count).result {[weak self] (datas, error) in
            guard let datas = datas else {
                self?.endRefresh.onNext(false)
                return
            }
            if datas.count == 0 {
                self?.endRefresh.onNext(true)
            } else {
                self?.endRefresh.onNext(false)
                self?.data.accept(self!.data.value + datas)
                self?.page = self!.page + 1
            }
        }
    }
    
    func sendComment(content : String) {
        self.service.sendComment(replayId: self.commentId, storyId: self.storyId, content: content).result { (commentInfo, error) in
            if let error = error {
                HUD.flash(.labeledError(title: nil, subtitle: error.localizedDescription))
                return
            }
            guard let commentInfo = commentInfo else {
                return
            }
            self.data.accept([commentInfo] + self.data.value)
        }
    }
    
    func changeCollectState() {
        guard let storyId = self.storyId else {
            return
        }
        collectState.accept(!collectState.value)
        STCollectService().changeCollectState(storyId: storyId, state: collectState.value).result { (error) in
            if error != nil {
                self.collectState.accept(!self.collectState.value)
                HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
            }
        }
    }
    
}
